'use client';

import React, { useState, useMemo } from 'react';
import { Input, Select, Space, Collapse, Tag, Divider, Typography } from 'antd';
import { SearchOutlined, ApiOutlined, InfoCircleOutlined } from '@ant-design/icons';
import styles from './ApiDocs.module.scss';

const { Title, Text } = Typography;

interface ApiParameter {
  name: string;
  type: string;
  required: boolean;
  in: 'query' | 'body' | 'header' | 'path';
  description: string;
}

interface ApiRequestBody {
  description: string;
  example: any;
}

interface ApiResponse {
  status: number;
  description: string;
  example: any;
}

interface ApiEndpoint {
  method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
  path: string;
  description: string;
  category: string;
  authentication?: boolean;
  permissions?: string[];
  parameters?: ApiParameter[];
  requestBody?: ApiRequestBody;
  responses: ApiResponse[];
}

const ApiDocsPage: React.FC = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<string | undefined>(undefined);
  const [selectedMethod, setSelectedMethod] = useState<string | undefined>(undefined);

  const apiEndpoints: ApiEndpoint[] = [
    {
      method: 'POST',
      path: '/api/auth/login',
      description: '用户登录',
      category: '身份认证',
      parameters: [
        { name: 'email', type: 'string', required: true, in: 'body', description: '用户邮箱' },
        { name: 'password', type: 'string', required: true, in: 'body', description: '用户密码' }
      ],
      requestBody: {
        description: '登录请求体',
        example: {
          email: 'user@example.com',
          password: 'password123'
        }
      },
      responses: [
        {
          status: 200,
          description: '登录成功',
          example: {
            success: true,
            message: '登录成功',
            data: {
              user: {
                id: 1,
                email: 'user@example.com',
                username: 'user'
              },
              token: 'jwt_token_here'
            }
          }
        },
        {
          status: 401,
          description: '登录失败',
          example: {
            success: false,
            message: '邮箱或密码错误'
          }
        }
      ]
    },
    {
      method: 'POST',
      path: '/api/auth/register',
      description: '用户注册',
      category: '身份认证',
      parameters: [
        { name: 'email', type: 'string', required: true, in: 'body', description: '用户邮箱' },
        { name: 'username', type: 'string', required: true, in: 'body', description: '用户名' },
        { name: 'password', type: 'string', required: true, in: 'body', description: '密码' }
      ],
      responses: [
        {
          status: 201,
          description: '注册成功',
          example: {
            success: true,
            message: '注册成功',
            data: {
              user: {
                id: 2,
                email: 'newuser@example.com',
                username: 'newuser'
              }
            }
          }
        }
      ]
    },
    {
      method: 'GET',
      path: '/api/auth/me',
      description: '获取当前用户信息',
      category: '身份认证',
      authentication: true,
      responses: [
        {
          status: 200,
          description: '获取成功',
          example: {
            success: true,
            data: {
              id: 1,
              email: 'user@example.com',
              username: 'user',
              role: 'user'
            }
          }
        }
      ]
    },
    {
      method: 'GET',
      path: '/api/admin/users',
      description: '获取用户列表',
      category: '用户管理',
      authentication: true,
      permissions: ['admin:users:read'],
      parameters: [
        { name: 'page', type: 'number', required: false, in: 'query', description: '页码' },
        { name: 'limit', type: 'number', required: false, in: 'query', description: '每页数量' },
        { name: 'search', type: 'string', required: false, in: 'query', description: '搜索关键词' }
      ],
      responses: [
        {
          status: 200,
          description: '获取成功',
          example: {
            success: true,
            data: {
              users: [
                {
                  id: 1,
                  email: 'user@example.com',
                  username: 'user',
                  role: 'user',
                  createdAt: '2024-01-01T00:00:00Z'
                }
              ],
              total: 1,
              page: 1,
              limit: 10
            }
          }
        }
      ]
    },
    {
      method: 'POST',
      path: '/api/sd/txt2img',
      description: '文本生成图像',
      category: 'AI功能',
      authentication: true,
      parameters: [
        { name: 'prompt', type: 'string', required: true, in: 'body', description: '正向提示词' },
        { name: 'negative_prompt', type: 'string', required: false, in: 'body', description: '负向提示词' },
        { name: 'width', type: 'number', required: false, in: 'body', description: '图像宽度' },
        { name: 'height', type: 'number', required: false, in: 'body', description: '图像高度' }
      ],
      requestBody: {
        description: '图像生成请求',
        example: {
          prompt: 'a beautiful landscape',
          negative_prompt: 'blurry, low quality',
          width: 512,
          height: 512,
          steps: 20,
          cfg_scale: 7
        }
      },
      responses: [
        {
          status: 200,
          description: '生成成功',
          example: {
            success: true,
            data: {
              images: ['base64_image_data'],
              parameters: {
                prompt: 'a beautiful landscape',
                steps: 20,
                cfg_scale: 7
              }
            }
          }
        }
      ]
    },
    {
      method: 'POST',
      path: '/api/ai-chat',
      description: 'AI对话',
      category: 'AI功能',
      authentication: true,
      parameters: [
        { name: 'message', type: 'string', required: true, in: 'body', description: '用户消息' },
        { name: 'model', type: 'string', required: false, in: 'body', description: 'AI模型' }
      ],
      responses: [
        {
          status: 200,
          description: '对话成功',
          example: {
            success: true,
            data: {
              response: 'AI回复内容',
              model: 'gpt-3.5-turbo',
              usage: {
                prompt_tokens: 10,
                completion_tokens: 20,
                total_tokens: 30
              }
            }
          }
        }
      ]
    },
    {
      method: 'GET',
      path: '/api/templates-db',
      description: '获取模板列表',
      category: '模板管理',
      authentication: true,
      parameters: [
        { name: 'category', type: 'string', required: false, in: 'query', description: '模板分类' },
        { name: 'search', type: 'string', required: false, in: 'query', description: '搜索关键词' }
      ],
      responses: [
        {
          status: 200,
          description: '获取成功',
          example: {
            success: true,
            data: [
              {
                id: 1,
                name: '风景模板',
                category: 'landscape',
                prompt: 'beautiful landscape',
                negative_prompt: 'ugly, blurry'
              }
            ]
          }
        }
      ]
    },
    {
      method: 'GET',
      path: '/api/config',
      description: '获取系统配置',
      category: '系统配置',
      responses: [
        {
          status: 200,
          description: '获取成功',
          example: {
            success: true,
            data: {
              appName: 'AIGC教育平台',
              version: '1.0.0',
              features: {
                registration: true,
                aiChat: true,
                imageGeneration: true
              }
            }
          }
        }
      ]
    }
  ];

  const categories = useMemo(() => {
    return Array.from(new Set(apiEndpoints.map(api => api.category)));
  }, []);

  const methods = useMemo(() => {
    return Array.from(new Set(apiEndpoints.map(api => api.method)));
  }, []);

  const filteredApis = useMemo(() => {
    return apiEndpoints.filter(api => {
      const matchesSearch = !searchTerm || 
        api.path.toLowerCase().includes(searchTerm.toLowerCase()) ||
        api.description.toLowerCase().includes(searchTerm.toLowerCase());
      
      const matchesCategory = !selectedCategory || api.category === selectedCategory;
      const matchesMethod = !selectedMethod || api.method === selectedMethod;
      
      return matchesSearch && matchesCategory && matchesMethod;
    });
  }, [searchTerm, selectedCategory, selectedMethod]);

  const getMethodColor = (method: string) => {
    const colors = {
      GET: 'blue',
      POST: 'green',
      PUT: 'orange',
      DELETE: 'red',
      PATCH: 'purple'
    };
    return colors[method as keyof typeof colors] || 'default';
  };

  return (
    <div className={styles.apiDocsContainer}>
      <div className={styles.header}>
        <Title level={1}>
          <ApiOutlined /> API 文档
        </Title>
        <p>
          这里是系统所有API接口的详细文档，包括请求参数、响应格式和使用示例。
        </p>
      </div>

      <div className={styles.filters}>
        <Space wrap size="middle">
          <Input
            placeholder="搜索API接口..."
            prefix={<SearchOutlined />}
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            style={{ width: 300 }}
          />
          <Select
            placeholder="选择分类"
            value={selectedCategory}
            onChange={setSelectedCategory}
            style={{ width: 150 }}
            allowClear
          >
            {categories.map(category => (
              <Select.Option key={category} value={category}>
                {category}
              </Select.Option>
            ))}
          </Select>
          <Select
            placeholder="选择方法"
            value={selectedMethod}
            onChange={setSelectedMethod}
            style={{ width: 120 }}
            allowClear
          >
            {methods.map(method => (
              <Select.Option key={method} value={method}>
                {method}
              </Select.Option>
            ))}
          </Select>
        </Space>
      </div>

      <div className={styles.apiList}>
        <Collapse
          items={filteredApis.map(api => ({
            key: api.path,
            label: (
              <div className={styles.apiHeader}>
                <Tag color={getMethodColor(api.method)} style={{ marginRight: '8px' }}>
                  {api.method}
                </Tag>
                <code className={styles.apiPath}>
                  {api.path}
                </code>
                <span style={{ color: '#b0b0b0', marginLeft: '12px' }}>{api.description}</span>
              </div>
            ),
            children: (
              <div className={styles.apiDetails}>
                <div className={styles.apiInfo}>
                  <Title level={4}>{api.description}</Title>
                  <Text>分类: {api.category}</Text>
                  {api.authentication && (
                    <div><Text type="warning">需要身份认证</Text></div>
                  )}
                  {api.permissions && api.permissions.length > 0 && (
                    <div>
                      <Text>所需权限: </Text>
                      {api.permissions.map(permission => (
                        <Tag key={permission} color="purple">{permission}</Tag>
                      ))}
                    </div>
                  )}
                </div>

                <Divider />

                {api.parameters && api.parameters.length > 0 && (
                  <div className={styles.parametersSection}>
                    <Title level={5}>请求参数</Title>
                    <div className={styles.parametersTable}>
                      <div className={styles.tableHeader}>
                        <div>参数名</div>
                        <div>类型</div>
                        <div>必填</div>
                        <div>位置</div>
                        <div>说明</div>
                      </div>
                      {api.parameters.map((param, index) => (
                        <div key={index} className={styles.tableRow}>
                          <div className={styles.paramName}>{param.name}</div>
                          <div>{param.type}</div>
                          <div>{param.required ? '是' : '否'}</div>
                          <div>{param.in}</div>
                          <div>{param.description}</div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {api.requestBody && (
                  <div className={styles.requestBodySection}>
                    <Title level={5}>请求体</Title>
                    <Text>{api.requestBody.description}</Text>
                    <div className={styles.codeBlock}>
                      <pre>{JSON.stringify(api.requestBody.example, null, 2)}</pre>
                    </div>
                  </div>
                )}

                {api.responses && api.responses.length > 0 && (
                  <div className={styles.responsesSection}>
                    <Title level={5}>响应</Title>
                    {api.responses.map((response, index) => (
                      <div key={index} className={styles.responseItem}>
                        <div className={styles.responseHeader}>
                          <Tag color={response.status >= 200 && response.status < 300 ? 'green' : 'red'}>
                            {response.status}
                          </Tag>
                          <span>{response.description}</span>
                        </div>
                        <div className={styles.codeBlock}>
                          <pre>{JSON.stringify(response.example, null, 2)}</pre>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )
          }))}
        />
      </div>

      {filteredApis.length === 0 && (
        <div className={styles.noResults}>
          <InfoCircleOutlined style={{ fontSize: 48, color: '#666' }} />
          <h3>未找到匹配的API</h3>
          <span>请尝试调整搜索条件</span>
        </div>
      )}
    </div>
  );
};

export default ApiDocsPage;